﻿// API请求封装
class Api {
    constructor(baseUrl = 'http://localhost:3000/api') {
        this.baseUrl = baseUrl;
        this.token = localStorage.getItem('token');
    }

    setToken(token) {
        this.token = token;
        localStorage.setItem('token', token);
    }

    clearToken() {
        this.token = null;
        localStorage.removeItem('token');
    }

    async request(endpoint, options = {}) {
        const headers = {
            'Content-Type': 'application/json',
            ...options.headers
        };

        if (this.token) {
            headers.Authorization = `Bearer ${this.token}`;
        }

        try {
            const response = await fetch(`${this.baseUrl}${endpoint}`, {
                ...options,
                headers
            });

            if (response.status === 401) {
                this.clearToken();
                window.location.href = '/login.html';
                return;
            }

            const data = await response.json();
            return data;
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    }

    // 用户认证相关方法
    async register(username, email, password) {
        const response = await this.request('/auth/register', {
            method: 'POST',
            body: JSON.stringify({ username, email, password })
        });
        this.setToken(response.token);
        return response;
    }

    async login(email, password) {
        const response = await this.request('/auth/login', {
            method: 'POST',
            body: JSON.stringify({ email, password })
        });
        this.setToken(response.token);
        return response;
    }

    async logout() {
        this.clearToken();
    }

    async getCurrentUser() {
        return this.request('/auth/me');
    }

    // 获取帖子列表
    async getPosts(page = 1) {
        return this.request(`/posts?page=${page}`);
    }

    // 发布新帖子
    async createPost(content, images = []) {
        return this.request('/posts', {
            method: 'POST',
            body: JSON.stringify({ content, images })
        });
    }

    // 添加评论
    async addComment(postId, content) {
        return this.request(`/posts/${postId}/comments`, {
            method: 'POST',
            body: JSON.stringify({ content })
        });
    }

    // 点赞/取消点赞
    async toggleLike(postId) {
        return this.request(`/posts/${postId}/like`, {
            method: 'POST'
        });
    }
}

// 导出API实例
export const api = new Api(); 